package com.freshmarket.freshmarket.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.freshmarket.freshmarket.dao.CouponMapper;
import com.freshmarket.freshmarket.dao.ProductMapper;
import com.freshmarket.freshmarket.dao.UserMapper;
import com.freshmarket.freshmarket.entity.Coupon;
import com.freshmarket.freshmarket.entity.Product;
import com.freshmarket.freshmarket.entity.User;
import com.freshmarket.freshmarket.entity.UserCoupon;
import com.freshmarket.freshmarket.dao.UserCouponMapper;
import com.freshmarket.freshmarket.exception.MyException;
import com.freshmarket.freshmarket.service.IUserCouponService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.freshmarket.freshmarket.utils.Result;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Squirrel
 * @since 2020-09-04
 */
@Service
public class UserCouponServiceImpl extends ServiceImpl<UserCouponMapper, UserCoupon> implements IUserCouponService {
    final UserCouponMapper userCouponMapper;

    public UserCouponServiceImpl(UserCouponMapper userCouponMapper) {
        this.userCouponMapper = userCouponMapper;
    }
    @Resource
    private CouponMapper couponMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private ProductMapper productMapper;

    @Override
    public void lessUserCouponNum(int userId,int couponId,int useNum){
    UserCoupon userCoupon = userCouponMapper.
            selectOne(new QueryWrapper<UserCoupon>().
                    eq("user_id",userId).eq("coupon_id", couponId));
    userCoupon.setUserCouponNum(userCoupon.getUserCouponNum()-useNum);
    userCouponMapper.updateById(userCoupon);
}


    /**
     * 新增直接发放券
     * @param userCoupon
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public Result insertDirect(UserCoupon userCoupon) throws Exception {
        //判断该优惠券该用户是否已经领取过
        UserCoupon coupon = userCouponMapper.selectByUserId(userCoupon.getUserId(), userCoupon.getCouponId());
        /*获取当前时间的date*/
        String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        Date nowTime = new SimpleDateFormat("yyyy-MM-dd").parse(format);
        /* 获取系统到期时间*/
        /*查询优惠券的到期时间*/
        Coupon coup = couponMapper.selectByCouponId(userCoupon.getCouponId());
        String pastdue = coup.getCouponPastdue();
        Date outTime = new SimpleDateFormat("yyyy-MM-dd").parse(pastdue);

        if(coupon != null && (outTime.getTime() >= nowTime.getTime())){
            throw new MyException("您已经领取过该优惠券,请不要重复领取！");
        }else{
            //新增优惠券记录
            userCoupon.setUserCouponGettime(pastdue);
            //判断优惠券是否足够
            if(coup.getCouponNum() >= userCoupon.getUserCouponNum()){
                //足够可以领取
                int insert = userCouponMapper.insert(userCoupon);
                //减少优惠券数量
                Integer couponNumber = coup.getCouponNum() - userCoupon.getUserCouponNum();
                Coupon cou = new Coupon();
                cou.setCouponId(userCoupon.getCouponId());
                cou.setCouponNum(couponNumber);
                int couCount = couponMapper.updateById(cou);
                if(insert > 0 && couCount>0) {
                    return new Result(true,200,"成功领取优惠券",null);
                }else{
                    throw new MyException("优惠券领取失败！");
                }
            }else{
                throw new MyException("优惠券库存不足！");
            }

        }

    }


    /**
     * 用户新增积分兑换券记录
     * @param userCoupon
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public Result insertScore(UserCoupon userCoupon) throws Exception {
        //1.查询该用户是否已经领取
        List<UserCoupon> listCoupons = userCouponMapper.selectByUserIdAndCoupId(userCoupon.getUserId(), userCoupon.getCouponId());

        //UserCoupon coupon = userCouponMapper.selectByUserId(userCoupon.getUserId(), userCoupon.getCouponId());

        /*获取当前时间的date*/
        String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        Date nowTime = new SimpleDateFormat("yyyy-MM-dd").parse(format);
        /* 获取系统到期时间*/
        /*查询优惠券的到期时间*/
        Coupon coup = couponMapper.selectByCouponId(userCoupon.getCouponId());
        String pastdue = coup.getCouponPastdue();
        Date outTime = new SimpleDateFormat("yyyy-MM-dd").parse(pastdue);

        //通过userCoupon查找用户,得到用户积分

        User user = userMapper.selectById(userCoupon.getUserId());


        if(listCoupons.size() != 0 && (outTime.getTime() >= nowTime.getTime())){
            throw new MyException("您已经领取过该优惠券,请不要重复领取！");

        }else {
            //新增积分兑换券记录
            //2.通过商品id查询scorePrice（针对积分换购的券）
            Integer scorePrice = coup.getCouponScorePrice();

            //积分兑换，(换购的价格)
            //3根据换购券的id查找商品id，根据商品id查找价格（折扣）

            if (coup.getCouponDiscount() <= 1) {
                Coupon cou = couponMapper.selectById(userCoupon.getCouponId());

                Product product = productMapper.selectById(cou.getProductId());

                //找到商品价格和折扣,计算所需积分，折扣券所需的积分
                int score = (int) Math.ceil(product.getProductPrice() * cou.getCouponDiscount());
                //判断积分是否足够
                if (user.getUserScore() >= score) {
                    //兑换
                    //4.兑换之后积分减少scorePrice
                    //新增积分兑换兑换记录
                    userCoupon.setUserCouponGettime(pastdue);

                    //减少用户积分
                    User userScore = new User();

                    userScore.setUserId(userCoupon.getUserId());
                    //需要更新的积分
                    Integer scoreUpdate = user.getUserScore() - score;
                    userScore.setUserScore(scoreUpdate);

                    int row = userMapper.updateById(userScore);
                    //判断优惠券是否足够
                    if (coup.getCouponNum() >= userCoupon.getUserCouponNum()) {
                        //足够可以领取
                        int insert = userCouponMapper.insert(userCoupon);
                        //减少优惠券数量（需要减少的数量）
                        Integer couponNumber = coup.getCouponNum() - userCoupon.getUserCouponNum();
                        Coupon co = new Coupon();
                        co.setCouponId(userCoupon.getCouponId());
                        co.setCouponNum(couponNumber);
                        int couCount = couponMapper.updateById(co);
                        if (insert > 0 && couCount > 0 && row > 0) {
                            return new Result(true, 200, "成功领取积分兑换券", null);
                        } else {

                            throw new MyException("积分兑换券领取失败！");
                        }
                    } else {
                        throw new MyException("积分兑换券券库存不足！");
                    }
                } else {
                    throw new MyException("您的积分余额不足！");
                }


            } else {
                // >1时

                //2.通过商品id查询scorePrice（针对积分换购的券）

                if (user.getUserScore() >= scorePrice) {
                    //兑换
                    //4.兑换之后积分减少scorePrice
                    //新增积分兑换兑换记录
                    userCoupon.setUserCouponGettime(pastdue);

                    //减少用户积分
                    User userScore = new User();

                    userScore.setUserId(userCoupon.getUserId());

                    Integer scoreUpdate = user.getUserScore() - scorePrice;
                    userScore.setUserScore(scoreUpdate);

                    int row = userMapper.updateById(userScore);
                    //判断优惠券是否足够
                    if (coup.getCouponNum() >= userCoupon.getUserCouponNum()) {
                        //足够可以领取
                        int insert = userCouponMapper.insert(userCoupon);
                        //减少优惠券数量
                        Integer couponNumber = coup.getCouponNum() - userCoupon.getUserCouponNum();
                        Coupon co = new Coupon();
                        co.setCouponId(userCoupon.getCouponId());
                        co.setCouponNum(couponNumber);
                        int couCount = couponMapper.updateById(co);
                        if (insert > 0 && couCount > 0 && row > 0) {
                            return new Result(true, 200, "成功领取积分兑换券", null);
                        } else {

                            throw new MyException("积分兑换券领取失败！");
                        }
                    } else {
                        throw new MyException("积分兑换券券库存不足！");
                    }
                } else {
                    throw new MyException("您的积分余额不足！");
                }



            }

        }
    }



}
